<template>
  <div class="login">
    <van-nav-bar title="登录" class="nav-top">
      <van-icon name="arrow-left" slot="left" @click="$router.back()" />
    </van-nav-bar>
    <van-form v-model="user" @submit="onSubmit" ref="loginForm">
      <van-field
        name="mobile"
        placeholder="请输入手机号"
        v-model="user.mobile"
        :rules="rules.mobile"
        type="number"
        maxlength="11"
      >
        <span slot="left-icon" class="iconfont toutiaoshouji"></span>
      </van-field>
      <van-field
        name="code"
        placeholder="请输入验证码"
        v-model="user.code"
        :rules="rules.code"
        type="number"
        maxlength="6"
      >
        <span slot="left-icon" class="iconfont toutiaoyanzhengma"></span>
        <template #button>
          <van-count-down
            v-if="countDown"
            :time="1000 * 60"
            format="sss"
            @finish="countDown = false"
          >
            <template #default="{ seconds }"> {{ (seconds + 1 + '').padStart(2, '0') }}s </template>
          </van-count-down>
          <van-button
            v-else
            round
            size="small"
            class="verification-code"
            type="default"
            native-type="button"
            @click="onCodeSms"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div class="login-btn">
        <van-button block type="info" native-type="submit" class="login-btn-bottom"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { login, sendSms } from '@/api/user';
import { Toast } from 'vant';

export default {
  name: 'login',
  data() {
    return {
      user: {
        mobile: '', // 手机号
        code: '', // 验证码
      },
      rules: {
        mobile: [
          {
            required: true,
            message: '请填写手机号',
          },
          {
            pattern: /^1[36789]\d{9}$/,
            message: '手机号格式错误',
          },
        ],
        code: [
          {
            required: true,
            message: '请填写验证码',
          },
          {
            pattern: /^\d{6}$/,
            message: '请输入6位数验证码',
          },
        ],
      },
      countDown: false,
    };
  },
  created() {},
  methods: {
    async onSubmit() {
      // 1.获取数据
      const users = this.user;

      // 2.表单验证
      Toast.loading({
        message: '登录中...',
        forbidClick: true, // 禁用背景点击
        duration: 0, // 持续时间，默认是2000，如果为0则持续展示
      });
      // 3.提交表单请求登录
      try {
        const { data } = await login(users);
        this.$store.commit('setUser', data.data);

        // console.log('登录成功', res);
        Toast.success('登录成功！');
        this.$router.back();
      } catch (err) {
        if (err.response.status === 400) {
          // console.log('手机号或验证码错误');
          Toast.fail('手机号或验证码错误');
        } else {
          // console.log('登录失败，请稍后重试！');
          Toast.fail('登录失败，请稍后重试！');
        }
      }

      // 4.根据响应结果处理后续操作
    },
    async onCodeSms() {
      try {
        await this.$refs.loginForm.validate('mobile');
        console.log('验证成功');
      } catch (err) {
        return console.log('验证失败', err);
      }
      this.countDown = true;
      try {
        const res = await sendSms(this.user.mobile);
        Toast.success('验证码发送成功');
        console.log('发送成功', res);
      } catch (err) {
        this.countDown = false;
        if (err.response.status === 429) {
          Toast.fail('请勿频繁发送验证码');
        } else {
          Toast.fail('验证码发送失败');
          console.log('发送失败', err);
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.login {
  .iconfont {
    font-size: 38px;
  }
  .verification-code {
    background-color: #eeeeee;
    width: 160px;
    height: 46px;
    font-size: 22px;
    color: #666;
  }
  .login-btn {
    padding: 53px 33px;
  }
  .login-btn-bottom {
    background-color: #66b1ff;
    border: none;
  }
}
</style>
